
//#include "antx.h"
#include "exmonwaiter.h"
#include <netinet/in.h>
#include <netdb.h>
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include "Debug.h"
#include "Helper.h"

//#define DFT_CAPACITY 64
//#define MAX_EXTENDSTEP 64
//#define MAX_HOSTSTRLEN 256

void *zexmon_command_waiter(void *arg)
{
	extern int sock_fd; 
	int new_fd;
	int *port = (int *)arg;
        DEBUG3("listen ", *port, " for zemon");
	struct sockaddr_in my_addr;
	if((sock_fd = socket(AF_INET,SOCK_STREAM,0))==-1)
	{
		perror("socket");
		exit(1);
        }
        my_addr.sin_family = AF_INET;
        my_addr.sin_port = htons( *port );
        my_addr.sin_addr.s_addr = INADDR_ANY;
        bzero(&(my_addr.sin_zero),8);
        int flags = 1;
        setsockopt(sock_fd ,SOL_SOCKET ,SO_REUSEADDR, &flags, sizeof(int));
        long lft = time(NULL);
        while(bind(sock_fd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))==-1)
        {
                usleep(10000);
                perror("bind");
                if(time(NULL) > lft + 120)
                        exit(1);
        }
        struct sockaddr_in their_addr;
        if(listen(sock_fd,1024)==-1) {
                perror("listen");
                exit(1);
        }
        while(1) {
                socklen_t sin_size = sizeof(struct sockaddr_in);
                if((new_fd = accept(sock_fd,(struct sockaddr *) &their_addr, &sin_size))==-1)
                {
                        perror("accept");
                        exit(1);
                }
                int numbytes = 0;
                char buff[1024];
                if((numbytes = read(new_fd, buff, 1024 )) != -1)
                {
                        buff[numbytes]= '\0';
                        if(strstr(buff,"ruok\n") != 0)
                                numbytes = sprintf(buff,"imok\n");
                        else if(strstr(buff,"stat") != 0)
                                numbytes = sprintf(buff,"stat is ok\n");
                        else if(strstr(buff,"kill") != 0)
                        {
                                printf("receive 'kill' command, exit !");
                                close(new_fd);
                                close(sock_fd);
                                exit(0);
                        }
                        if(send(new_fd,buff, numbytes, 0)==-1)
                                perror("send");
                }
                close(new_fd);
        }
        close(sock_fd);
        sock_fd = 0;
        return NULL;
}

void *extern_deamon_checker(void *arg)
{
	while(true)
	{
           sleep(30);
	   Helper *p = Helper::Instance();
	   if(p != NULL)
		   p->Check( arg );
	}       
	return NULL;
}


